package com.qf.flash.mvp.presenter;

import android.text.TextUtils;

import com.hyphenate.chat.EMClient;
import com.qf.dblib.dao.entity.ChatUserBean;
import com.qf.dblib.dao.entity.InviteMessage;
import com.qf.dblib.dao.entity.UserInfo;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.app.MyApp;
import com.qf.flash.event.ChatEvent;
import com.qf.flash.http.HttpManager;
import com.qf.flash.mvp.contract.NewFriendInviteContract;
import com.qf.flash.ui.chat.db.InviteMessgeDao;
import com.qf.flash.utils.AppToast;
import com.qf.flash.utils.LogUtil;
import com.qf.flash.utils.MyUtil;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BasePresenter;
import com.qf.flashlib.base.BaseSubscriber;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.RxUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

import static com.qf.flash.constant.Constant.ACTION_CONTACT_CHANAGED;
import static com.qf.flash.constant.Constants.BEINVITEED;

public class NewFriendInvitePresenter extends BasePresenter<NewFriendInviteContract.View> implements NewFriendInviteContract.Presenter {
    String userid = UserMgr.getInstance().getLoginUser().getUid();

    @Override
    public void getChatUserList(int page, int pageSize) {
        InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(MyApp.getAppContext());
        List<InviteMessage> messagesList = inviteMessgeDao.getMessagesList();
        String ids = "";
        for (int i = 0; i < messagesList.size(); i++) {
            if (messagesList.get(i).getStatus().equals(BEINVITEED)) {
                if (i == 0) {
                    ids = messagesList.get(i).getFrom();
                } else {
                    ids = ids + "," + messagesList.get(i).getFrom();
                }
            }
        }
        if (MyUtil.isNullOrEmpty(ids)) {
            mRootView.setUi(null);
        } else {

            addSubscription(HttpManager.getInstance().getGsonHttpApi()
                    .CHAT_USER_LIST(userid, ids, page, pageSize)
                    .compose(RxUtils.<List<ChatUserBean>>handleResult())
                    .compose(RxUtils.<List<ChatUserBean>>io_main())
                    .subscribeWith(new BaseSubscriber<List<ChatUserBean>>(mRootView) {
                        @Override
                        public void onSuccess(List<ChatUserBean> beans) {
                            mRootView.setUi(beans);
                        }

                    })

            );
        }
    }

    @Override
    public void addFriend(String codeId) {
//        addSubscription(HttpManager.getInstance().getGsonHttpApi()
//                .ADD_FRIEND(userid, codeId)
//                .compose(RxUtils.<Object>handleResult())
//                .compose(RxUtils.<Object>io_main())
//                .subscribeWith(new BaseSubscriber<Object>(mRootView) {
//                    @Override
//                    public void onSuccess(Object object) {
//                        LogUtil.d("添加好友----onSuccess:");
//                        AppToast.showToast("添加好友成功");
//                        EventBus.getDefault().post(new ChatEvent(ACTION_CONTACT_CHANAGED));
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        super.onError(e);
//                        LogUtil.d("添加好友----onError:" + e.getMessage());
//                        AppToast.showToast("添加好友：" + e.getMessage());
//                    }
//                })
//
//        );
        HttpManager.getInstance().getGsonHttpApi().USER_INFO(codeId, UserMgr.getInstance().getLoginUser().getUid())
                .compose(RxUtils.io_main())
                .compose(RxUtils.handleResult())
                .subscribe(new Consumer<UserInfo>() {
                    @Override
                    public void accept(UserInfo userInfo) throws Exception {
                        if (mRootView != null)
                            realAddFriend(codeId);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        FlashLib.showToast("ID不存在");
                        if (mRootView != null)
                            mRootView.addFriendResult(false);
                    }
                });

    }

    public void receiveInvite(String codeId) {
        addSubscription(HttpManager.getInstance().getGsonHttpApi()
                .ADD_FRIEND(userid, codeId)
                .compose(RxUtils.<Object>handleResult())
                .compose(RxUtils.<Object>io_main())
                .subscribeWith(new BaseSubscriber<Object>(mRootView) {
                    @Override
                    public void onSuccess(Object object) {
                        LogUtil.d("添加好友----onSuccess:");
                        AppToast.showToast("添加好友成功");
                        EventBus.getDefault().post(new ChatEvent(ACTION_CONTACT_CHANAGED));
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        LogUtil.d("添加好友----onError:" + e.getMessage());
                        AppToast.showToast("添加好友：" + e.getMessage());
                    }
                })

        );
    }

    private void realAddFriend(String codeId) {
        addSubscription(Observable.create((ObservableOnSubscribe<String>) e -> {
            if (TextUtils.isEmpty(codeId)) {
                e.onError(new Throwable("ID不能为空"));
            } else if (EMClient.getInstance().getCurrentUser().equals(codeId)) {
                e.onError(new Throwable("不能添加自己"));
            } else if (EMClient.getInstance().contactManager().getBlackListFromServer().contains(codeId)) {
                e.onError(new Throwable("此用户已是你好友(被拉黑状态)，从黑名单列表中移出即可"));
            } else if (EMClient.getInstance().contactManager().getAllContactsFromServer().contains(codeId)) {
                e.onError(new Throwable("此用户已是你好友"));
            } else {
                EMClient.getInstance().contactManager().addContact(codeId, "加个好友呗");
                e.onNext("已发送好友请求");
            }
        }).compose(RxUtils.io_main())
                .subscribe(s -> {
                    FlashLib.showToast(s);
                    EventBus.getDefault().post(new ChatEvent(ACTION_CONTACT_CHANAGED));
                    mRootView.addFriendResult(true);
                }, throwable -> {
                    mRootView.addFriendResult(false);
                    FlashLib.showToast(throwable.getMessage());
                }));
    }


}
